
package com.jf.cloud.product.controller.admin;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jf.cloud.api.auth.constant.SysTypeEnum;
import com.jf.cloud.api.combo.feign.ComboFeignClient;
import com.jf.cloud.api.multishop.bo.EsShopDetailBO;
import com.jf.cloud.api.multishop.constant.ShopStatus;
import com.jf.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.jf.cloud.api.multishop.feign.ShopSubstituteSalesFeignClient;
import com.jf.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.jf.cloud.api.platform.feign.ConfigFeignClient;
import com.jf.cloud.api.platform.vo.OfflineHandleEventVO;
import com.jf.cloud.api.product.util.ProductLangUtil;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.constant.StatusEnum;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.product.constant.SpuType;
import com.jf.cloud.common.product.constant.SupplierDeliveryType;
import com.jf.cloud.common.product.constant.SupplierSpuType;
import com.jf.cloud.common.product.dto.SpuDTO;
import com.jf.cloud.common.product.vo.*;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.ExcelUtil;
import com.jf.cloud.common.util.Json;
import com.jf.cloud.common.vo.ShopSubstituteSalesVO;
import com.jf.cloud.common.product.constant.SpuStatus;
import com.jf.cloud.product.dto.SpuPageSearchDTO;
import com.jf.cloud.product.handler.ProductCommentWriteHandler;
import com.jf.cloud.product.listener.SpuExcelListener;
import com.jf.cloud.product.model.SpuConsignmentChange;
import com.jf.cloud.product.model.SpuExtension;
import com.jf.cloud.product.service.*;
import com.jf.cloud.product.vo.CategoryShopVO;
import com.jf.cloud.product.vo.SpuExcelVO;
import com.jf.cloud.product.vo.SupplierSpuExcelVO;
import com.jf.cloud.product.vo.SupplierSpuVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.collections.CollectionUtils;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * spu信息
 *
 * @author zz
 * @date 2020-10-28 15:27:24
 */
@RestController("adminSpuController")
@RequestMapping("/mp/spu")
@Tag(name = "admin-spu信息")
public class SpuController {

    @Autowired
    private SpuService spuService;
    @Autowired
    private SpuExcelService spuExcelService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private ShopDetailFeignClient shopDetailFeignClient;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private CategoryShopService categoryShopService;
    @Autowired
    private ShopSubstituteSalesFeignClient shopSubstituteSalesFeignClient;
    @Autowired
    private SpuConsignmentChangeService spuConsignmentChangeService;
    @Autowired
    private ShopCartService shopCartService;
    @Autowired
    private GiveawaySpuService giveawaySpuService;
    @Autowired
    private GiveawayService giveawayService;
    @Autowired
    private ComboFeignClient comboFeignClient;
    @Autowired
    private ConfigFeignClient configFeignClient;

    @GetMapping
    @Operation(summary = "获取spu信息" , description = "根据spuId获取spu信息")
    public ServerResponseEntity<SpuVO> getBySpuId(@RequestParam Long spuId) {
        // 获取spu信息
        SpuVO spuVO = spuService.getBySpuId(spuId);
        if (Objects.equals(spuVO.getSupplierSpuType(), SupplierSpuType.CONSIGNMENT.value()) && !Objects.isNull(spuVO.getSupplierSpuId())){
            //处理返回的代销商品信息
            disposeSpuMsg(spuVO);
            //返回商家代销设置
            setSalesMsg(spuVO);
            //供应商商品信息
            SpuVO supplierSpu = spuService.getBySpuId(spuVO.getSupplierSpuId());
            spuVO.setSupplierSpuStatus(supplierSpu.getStatus());
            spuVO.setSupplierSpuCode(supplierSpu.getSpuCode());
            if (Objects.equals(spuVO.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value()) && Objects.equals(supplierSpu.getStatus(),StatusEnum.DELETE.value())){
                spuVO.setSupplierDeliveryType(SupplierDeliveryType.SHOP_DELIVERY.value());
            }
        }
        Integer sysType = AuthUserContext.get().getSysType();
        if (!Objects.equals(sysType, SysTypeEnum.MULTISHOP.value()) && !Objects.equals(spuVO.getSupplierSpuType(),SupplierSpuType.YES.value())){
            if (!Objects.equals(spuVO.getShopId(), AuthUserContext.get().getTenantId()) && !Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId()) ) {
                return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
            }
        }
        List<SpuAttrValueVO> spuAttrsBySpuId = spuAttrValueService.getSpuAttrsBySpuId(spuId);
        spuVO.setSpuAttrValues(spuAttrsBySpuId);
        SpuExtension spuExtension = spuService.getSpuExtension(spuId);
        spuVO.setTotalStock(spuExtension.getActualStock());
        spuVO.setSaleNum(spuExtension.getSaleNum());
        // 物流模板
        SpuVO.DeliveryModeVO deliveryModeVO = Json.parseObject(spuVO.getDeliveryMode(), SpuVO.DeliveryModeVO.class);
        spuVO.setDeliveryModeVO(deliveryModeVO);
        // 品牌信息
        spuVO.setBrand(brandService.getByBrandId(spuVO.getBrandId()));
        // sku信息
        if (Objects.equals(spuVO.getSupplierSpuType(),SupplierSpuType.CONSIGNMENT.value())){
            //代销商品
            spuVO.setSkus(skuService.listConsignmentSku(spuVO,false));
        }else {
            //其他商品（商家商品，供应商商品）
            spuVO.setSkus(skuService.listSkuAllInfoBySpuId(spuId, false));
        }
        loadSpuAttrs(spuVO);
        // 平台分类、店铺分类信息
        spuVO.setCategory(categoryService.getInfo(spuVO.getCategoryId()));
        ProductLangUtil.category(spuVO.getCategory());
        if (Objects.nonNull(spuVO.getShopCategoryId()) && !Objects.equals(spuVO.getShopCategoryId(), Constant.DEFAULT_ID)) {
            spuVO.setShopCategory(categoryService.getInfo(spuVO.getShopCategoryId()));
            if (!Objects.isNull(spuVO.getShopCategory())){
                ProductLangUtil.category(spuVO.getShopCategory());
            }
        }
        // 是否为套餐商品
        Boolean data = comboFeignClient.checkComboSpu(spuId, AuthUserContext.get().getTenantId()).getData();
        spuVO.setIsComboSpu(data);
        return ServerResponseEntity.success(spuVO);
    }

    private void setSalesMsg(SpuVO spuVO){
        if (Objects.equals(AuthUserContext.get().getSysType(),SysTypeEnum.MULTISHOP.value())){
            Long shopId = AuthUserContext.get().getTenantId();
            //获取商家代销设置
            ServerResponseEntity<ShopSubstituteSalesVO> shopSubstituteSales = shopSubstituteSalesFeignClient.getByShopSubstituteSalesId(shopId);
            spuVO.setSalesType(shopSubstituteSales.getData().getSalesType());
            spuVO.setSalesPriceType(shopSubstituteSales.getData().getSalesPriceType());
            if(Objects.equals(spuVO.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value())){
                spuVO.setSalesPrice(shopSubstituteSales.getData().getSalesPrice());
            }
        }
    }
    /**
     * 处理代销商品信息
     * @param spuVO
     * @return
     */
    private void   disposeSpuMsg(SpuVO spuVO){
        Long spuId = spuVO.getSpuId();
        //获取代销商品基本信息是否改变
        SpuConsignmentChange spuConsignmentChange = spuConsignmentChangeService.consignmentChange(spuId);
        if (Objects.isNull(spuConsignmentChange)){
            return;
        }
        //获取供应商信息
        SpuVO supplierSpu = spuService.getBySpuId(spuVO.getSupplierSpuId());
        List<SpuLangVO> spuLangList = spuVO.getSpuLangList();
        List<SpuLangVO> supplierSpuLangList = supplierSpu.getSpuLangList();
        Map<Integer, SpuLangVO> supplierSpuLangVOMap = supplierSpuLangList.stream().collect(Collectors.toMap(SpuLangVO::getLang, e -> e));
        if (Objects.equals(spuVO.getSupplierDeliveryType(),SupplierDeliveryType.SUPPLIER_DELIVERY.value())){
            //名称
            if (Objects.equals(spuConsignmentChange.getNameChange(),0)){
                for (SpuLangVO spuLangVO : spuLangList) {
                    SpuLangVO langVO = supplierSpuLangVOMap.get(spuLangVO.getLang());
                    if (Objects.isNull(langVO)){
                        continue;
                    }
                    spuLangVO.setSpuName(langVO.getSpuName());
                }
            }
            //图片
            if (Objects.equals(spuConsignmentChange.getImageChange(),0)){
                spuVO.setImgUrls(supplierSpu.getImgUrls());
                spuVO.setMainImgUrl(supplierSpu.getMainImgUrl());
            }
            //视频
            if (Objects.equals(spuConsignmentChange.getVideoChange(),0)){
                spuVO.setVideo(supplierSpu.getVideo());
            }
            //卖点
            if (Objects.equals(spuConsignmentChange.getSellingPointChange(),0)){
                for (SpuLangVO spuLangVO : spuLangList) {
                    SpuLangVO langVO = supplierSpuLangVOMap.get(spuLangVO.getLang());
                    if (Objects.isNull(langVO)){
                        continue;
                    }
                    spuLangVO.setSellingPoint(langVO.getSellingPoint());
                }
            }
            //计量单位
            if (Objects.equals(spuConsignmentChange.getMeasureUnitChange(),0)){
                spuVO.setMeasureUnit(supplierSpu.getMeasureUnit());
            }
            //spuCod
            if (Objects.equals(spuConsignmentChange.getSpuCodeChange(),0)){
                spuVO.setSpuCode(supplierSpu.getSpuCode());
            }
            //详情描述
            if (Objects.equals(spuConsignmentChange.getDetailChange(),0)){
                    spuVO.setDetail(supplierSpu.getDetail());
            }
            //品牌
            if (Objects.equals(spuConsignmentChange.getBrandChange(),0)){
                // 品牌信息
                spuVO.setBrand(brandService.getByBrandId(supplierSpu.getBrandId()));
            }
            //序号
            spuVO.setSeq(supplierSpu.getSeq());
        }

    }

    @PostMapping
    @Operation(summary = "保存spu信息" , description = "保存spu信息")
    public ServerResponseEntity<Long> save(@Valid @RequestBody SpuDTO spuDTO) {
        spuDTO.setStatus(StatusEnum.ENABLE.value());
        if (!Objects.equals(spuDTO.getSpuType(), SpuType.ACTIVE.value())){
            spuDTO.setSpuType(SpuType.NORMAL.value());
        }
        spuService.save(spuDTO);
        return ServerResponseEntity.success(spuDTO.getSpuId());
    }

    @PutMapping
    @Operation(summary = "更新spu信息" , description = "更新spu信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody SpuDTO spuDTO) {
        SpuVO spuDb = spuService.getBySpuId(spuDTO.getSpuId());
        if (!Objects.equals(spuDb.getShopId(), AuthUserContext.get().getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        spuService.update(spuDTO);
        //  清除购物车数量缓存
        shopCartService.removeShopCartItemCache(Collections.singletonList(spuDTO.getSpuId()));
        //校验赠品活动
//        giveawayService.checkGiveawaySpuPrice(spuDTO);
        return ServerResponseEntity.success();
    }


    @DeleteMapping
    @Operation(summary = "删除spu信息" , description = "根据spu信息id删除spu信息")
    public ServerResponseEntity<Void> delete(@RequestParam Long spuId) {
        SpuVO spuDb = spuService.getBySpuId(spuId);
        Long shopId = AuthUserContext.get().getTenantId();
        if (!Objects.equals(spuDb.getShopId(), shopId) && !Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        //判断是否包含赠品活动、判断商品是否为套餐活动(正在进行的)的主商品
        checkBeforeDeleteSpu(spuId,shopId);

        spuService.deleteById(spuId);
        //  清除购物车数量缓存
        shopCartService.removeShopCartItemCache(Collections.singletonList(spuId));
        return ServerResponseEntity.success();
    }

    private void checkBeforeDeleteSpu(Long spuId, Long shopId) {
        Boolean data = comboFeignClient.checkComboSpu(spuId, shopId).getData();
        if (data){
            throw new LuckException("参加以下活动的商品不能被删除：优惠套餐");
        }
        GiveawayVO giveawayVO = giveawayService.getBySpuId(spuId);
        List<GiveawaySpuVO> giveawaySpuVOs = giveawaySpuService.getBySpuId(spuId);
        if (giveawayVO != null || CollectionUtils.isNotEmpty(giveawaySpuVOs)) {
            //参加以下活动的商品不能被删除：赠品
            throw new LuckException("参加以下活动的商品不能被删除：赠品");
        }
    }

    @PutMapping("/update_spu_data")
    @Operation(summary = "修改spu（名称、价格、库存、序号）信息" , description = "更新spu信息")
    public ServerResponseEntity<Void> updateSpuData(@RequestBody SpuDTO spuDTO) {
        SpuVO spuDb = spuService.getBySpuId(spuDTO.getSpuId());
        if (!Objects.equals(spuDb.getShopId(), AuthUserContext.get().getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        spuService.updateSpuOrSku(spuDTO);

        //  清除购物车数量缓存
        shopCartService.removeShopCartItemCache(Collections.singletonList(spuDTO.getSpuId()));
        return ServerResponseEntity.success();
    }


    /**
     * 更新商品状态
     */
    @PutMapping("/prod_status")
    @Operation(summary = "商品上下架" , description = "商品上下架")
    public ServerResponseEntity<Void> spuChangeStatus(@RequestBody SpuPageSearchDTO spuDTO) {
        if (Objects.nonNull(spuDTO.getSpuId())) {
            spuDTO.setSpuIds(Collections.singletonList(spuDTO.getSpuId()));
        }
        if (CollUtil.isEmpty(spuDTO.getSpuIds())) {
            throw new LuckException("商品id不能为空");
        }
        Long shopId = AuthUserContext.get().getTenantId();
        List<SpuVO> spuList = spuService.listSpuBySpuIds(spuDTO.getSpuIds());

        if(Objects.equals(spuDTO.getStatus(),StatusEnum.ENABLE.value()) && !Objects.equals(AuthUserContext.get().getTenantId(), Constant.PLATFORM_SHOP_ID)){
            // 上架商品时，需要根据店铺状态判断是否可以上架商品
            ServerResponseEntity<EsShopDetailBO> shopRequest = shopDetailFeignClient.getShopByShopId(AuthUserContext.get().getTenantId());
            EsShopDetailBO shopDetail = shopRequest.getData();
            if (!Objects.equals(shopDetail.getShopStatus(), ShopStatus.OPEN.value())) {
                // 合同到期
                if(shopDetail.getContractEndTime().compareTo(new Date()) < 0){
                    throw new LuckException("店铺有效期已过，不能进行此操作，请联系管理员后重试");
                }
                throw new LuckException("店铺处于违规下线状态，不能上架商品");
            }
        }
        for (SpuVO spuVO : spuList) {
            if(Objects.equals(spuDTO.getStatus(),StatusEnum.ENABLE.value())) {
                if(!Objects.equals(spuVO.getSpuType(), SpuType.SCORE.value())){
                    CategoryVO category = categoryService.getInfo(spuVO.getCategoryId());
                    if (category == null || Objects.equals(category.getStatus(), StatusEnum.DISABLE.value())) {
                        // 平台分类处于下线中，商品不能上架，请联系管理员后再进行操作
                        throw new LuckException("商品【" + spuVO.getName() + "】的平台分类处于下线中，商品不能上架，请联系管理员后再进行操作");
                    }
                    boolean write = Objects.equals(spuVO.getSpuMold(), 1) && !Objects.equals(0, spuVO.getWriteOffNum()) &&
                            Objects.equals(spuVO.getWriteOffTime(), 0) && Objects.nonNull(spuVO.getWriteOffEnd()) && new Date().after(spuVO.getWriteOffEnd());
                    if(write){
                        //商品已过核销有效期
                        throw new LuckException("该商品已过核销有效期");
                    }
                    if(!Objects.equals(spuVO.getSpuType(), SpuType.SCORE.value())) {
                        CategoryVO shopCategory = categoryService.getById(spuVO.getShopCategoryId());
                        if (shopCategory == null || Objects.equals(shopCategory.getStatus(), StatusEnum.DISABLE.value())) {
                            // 本店分类处于下线中，商品不能上架
                            throw new LuckException("商品【" + spuVO.getName() + "】的本店分类处于下线中，商品不能上架");
                        }
                    }
                }
                // 商家代销的供应商商品上架，如果是仓库发货，需要检验是否存在物流模板id了
                if (Objects.equals(spuVO.getSupplierSpuType(), SupplierDeliveryType.SHOP_DELIVERY.value()) && Objects.isNull(spuVO.getDeliveryTemplateId())) {
                    // 请先设置商品的物流模板
                    throw new LuckException("请先设置商品的物流模板： 商品名称【" + spuVO.getName() + "】");
                }
                // 如果商品正在下架，但又是活动商品，代表这个商品所属的活动被平台下架了
                if (Objects.equals(spuVO.getSpuType(), SpuType.SECKILL.value())) {
                    throw new LuckException("商品【" + spuVO.getName() + "】所属的秒杀活动处于违规下线中，商品不能上架");
                }
                if (Objects.equals(spuVO.getSpuType(), SpuType.GROUP.value())) {
                    throw new LuckException("商品【" + spuVO.getName() + "】所属的团购活动处于违规下线中，商品不能上架");
                }
            }
            //供应商商品
            if (SupplierSpuType.YES.value().equals(spuDTO.getSupplierSpuType())){
                SpuVO spuVo = spuService.getSpuByShopIdAndSupplierSpuId(shopId, spuDTO.getSpuId());
                if (!Objects.isNull(spuVo)){
                    spuDTO.setSpuId(spuVo.getSpuId());
                    spuDTO.setShopId(spuVo.getShopId());
                    spuVO.setShopId(spuVo.getShopId());
                }
            }
            if (!Objects.equals(spuVO.getShopId(), shopId) && !Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
                return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
            }
        }
        // 是否开启“商品发布时审核”，若开启，上架修改状态为“待审核”【平台端不用审核】
        String prodSwitchConfig = configFeignClient.getConfig(Constant.SPU_SWITCH_CONFIG).getData();
        if (SpuStatus.PUT_SHELF.value().equals(spuDTO.getStatus())
                && !SysTypeEnum.PLATFORM.value().equals(AuthUserContext.get().getSysType())
                && !ObjectUtils.isEmpty(prodSwitchConfig)) {
            Boolean spuAudit = JSON.parseObject(prodSwitchConfig, new TypeReference<Map<String, Boolean>>(){})
                    .getOrDefault("spuAudit", false);
            if (spuAudit) {
                spuDTO.setStatus(SpuStatus.PUBLISH_WAIT_AUDIT.value());
            }
        }
        spuBatchUpdateStatus(spuDTO);
        for (SpuVO spuVO : spuList) {
            spuService.removeSpuCacheBySpuId(spuVO.getSpuId());
        }
        //  清除购物车数量缓存
        shopCartService.removeShopCartItemCache(spuDTO.getSpuIds());
        return ServerResponseEntity.success();
    }

    @GetMapping("/sold_excel")
    @Operation(summary = "导出excel" , description = "导出商品excel")
    public ServerResponseEntity<Void> spuSoldExcel(HttpServletResponse response, @ParameterObject SpuPageSearchDTO spuDTO) {
        List<SpuExcelVO> list = spuExcelService.excelSpuList(spuDTO);
        ExcelUtil.soleExcelWithHandler(response, list, SpuExcelVO.EXCEL_NAME, SpuExcelVO.MERGE_ROW_INDEX,
                SpuExcelVO.MERGE_COLUMN_INDEX, new ProductCommentWriteHandler(SysTypeEnum.MULTISHOP.value()), SpuExcelVO.class);
        return ServerResponseEntity.success();
    }

    @GetMapping("/down_model")
    @Operation(summary = "导出商品excel模板" , description = "导出商品excel模板")
    public ServerResponseEntity<Void> downloadModel(HttpServletResponse response) {
        spuExcelService.downloadModel(response);
        return ServerResponseEntity.success();
    }

    @Operation(summary = "导入文件")
    @PostMapping("/export_excel")
    public ServerResponseEntity<String> exportExcel(@RequestParam("excelFile") MultipartFile file){
        if(file == null) {
            throw new LuckException("网络繁忙，请稍后重试");
        }
        String info = null;
        try {
            Map<Integer, List<String>> errorMap = new HashMap<>(8);
            EasyExcel.read(file.getInputStream(), SpuExcelVO.class, new SpuExcelListener(spuExcelService, errorMap)).sheet().doRead();
            info = spuExcelService.spuExportError(errorMap);
        } catch (IOException e) {
            throw new LuckException(e.getMessage());
        }
        return ServerResponseEntity.success(info);
    }

    /**
     * spu批量上下架
     * @param spuDTO
     */
    private void spuBatchUpdateStatus(SpuPageSearchDTO spuDTO) {
        List<Long> spuIds = spuDTO.getSpuIds();
        Integer status = spuDTO.getStatus();
        spuDTO.setStatus(null);
        List<SpuVO> spuList = new ArrayList<>();
        if (Objects.equals(spuDTO.getSupplierSpuType(), SupplierSpuType.CONSIGNMENT.value())){
            spuList = spuService.supplierSpuList(spuDTO);
        }else {
            spuList = spuService.list(spuDTO);
        }
        if (CollUtil.isEmpty(spuList)) {
            throw new LuckException("获取不到该商品信息，请刷新后重试");
        }
        checkUpdateStatusData(spuList, status);
        if (CollUtil.isEmpty(spuIds)) {
            throw new LuckException("您所选择的商品中没有符合操作条件的商品");
        }
        spuService.batchChangeSpuStatus(spuIds, status);
    }

    /**
     * 加载spu属性列表
     * @param spuVO
     */
    private void loadSpuAttrs(SpuVO spuVO) {
        Map<Long, SpuAttrValueVO> attrMap = null;
        if (CollUtil.isNotEmpty(spuVO.getSpuAttrValues())) {
            attrMap = spuVO.getSpuAttrValues().stream().collect(Collectors.toMap(SpuAttrValueVO::getAttrId, s -> s));
        } else {
             attrMap = new HashMap<>(1);
        }
        List<AttrVO> attrList = attrService.getAttrsByCategoryIdAndAttrType(spuVO.getCategoryId());
        List<SpuAttrValueVO> spuAttrValues = new ArrayList<>();
        for (AttrVO attrVO : attrList) {
            SpuAttrValueVO spuAttrValueVO = attrMap.get(attrVO.getAttrId());
            SpuAttrValueVO newSpuAttrValue = new SpuAttrValueVO();
            if (Objects.nonNull(spuAttrValueVO)) {
                boolean hasValue = false;
                for (AttrValueVO attrValue : attrVO.getAttrValues()) {
                    if (Objects.equals(attrValue.getAttrValueId(), spuAttrValueVO.getAttrValueId())) {
                        hasValue = true;
                        break;
                    }
                }
                if (hasValue || CollUtil.isEmpty(attrVO.getAttrValues())) {
                    spuAttrValues.add(spuAttrValueVO);
                    continue;
                }
                newSpuAttrValue.setSpuAttrValueId(spuAttrValueVO.getSpuAttrValueId());
            }
            newSpuAttrValue.setAttrId(attrVO.getAttrId());
            newSpuAttrValue.setAttrName(attrVO.getName());
            newSpuAttrValue.setSearchType(attrVO.getSearchType());
            spuAttrValues.add(newSpuAttrValue);
        }
        spuVO.setSpuAttrValues(spuAttrValues);
    }

    /**
     * 校验spu上下架信息
     * @param list 商品列表
     * @param status 更新的状态
     * @return
     */
    private void checkUpdateStatusData(List<SpuVO> list, Integer status) {
        ProductLangUtil.spuList(list);
        Long shopId = AuthUserContext.get().getTenantId();
        Integer sysType = AuthUserContext.get().getSysType();
        ServerResponseEntity<EsShopDetailBO> shopRequest = shopDetailFeignClient.getShopByShopId(shopId);
        EsShopDetailBO shopDetail = shopRequest.getData();
        if (Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE.value()) || Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE_AWAIT_AUDIT.value())) {
            throw new LuckException("店铺处于违规下线中，不能修改商品");
        }
        for (SpuVO spu : list) {
            if (!Objects.equals(spu.getShopId(), shopId) && !Objects.equals(AuthUserContext.get().getTenantId(), Constant.PLATFORM_SHOP_ID)) {
                throw new LuckException(ResponseEnum.UNAUTHORIZED);
            }
            // 商品状态不为启用或未启用状态
            if (!Objects.equals(spu.getStatus(), StatusEnum.ENABLE.value())
                    && !Objects.equals(spu.getStatus(), StatusEnum.DISABLE.value())) {
                throw new LuckException("商品(" + spu.getName() + ")不能进行上下架操作");
            }
            if(Objects.equals(status, StatusEnum.ENABLE.value()) && !Objects.equals(spu.getSpuType(), SpuType.SCORE.value())){
                CategoryVO category = categoryService.getById(spu.getCategoryId());
                if (!Objects.equals(category.getStatus(), StatusEnum.ENABLE.value())){
                    throw new LuckException("商品(" + spu.getName() +")所属的平台分类处于下线中，商品不能进行上架操作，请联系管理员后再进行操作");
                }
                if (!Objects.equals(spu.getSpuType(), SpuType.SCORE.value())) {
                    CategoryVO shopCategory = categoryService.getById(spu.getShopCategoryId());
                    if (!Objects.equals(shopCategory.getStatus(), StatusEnum.ENABLE.value())) {
                        throw new LuckException("商品(" + spu.getName() + ")所属的店铺分类处于下线中，商品不能进行上架操作");
                    }
                    CategoryShopVO categoryShopVO = categoryShopService.getByShopIdAndCategoryId(spu.getShopId(), spu.getCategoryId(), sysType);
                    if (Objects.isNull(categoryShopVO)) {
                        throw new LuckException("商品(" + spu.getName() + ")所属的平台分类与店铺的签约关系已失效，商品不能进行上架操作");
                    }
                }
            }
        }
    }

    @PostMapping("/offline")
    @Operation(summary = "下线商品" , description = "下线商品")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEventDTO offlineHandleEventDto) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        SpuVO spuVO = spuService.getBySpuId(offlineHandleEventDto.getHandleId());
        if (Objects.isNull(spuVO)) {
            throw new LuckException(ResponseEnum.DATA_ERROR);
        }
        spuService.offline(offlineHandleEventDto);
        spuService.removeSpuCacheBySpuId(offlineHandleEventDto.getHandleId());
        return ServerResponseEntity.success();
    }

    @PostMapping("/batch_offline")
    @Operation(summary = "批量下线商品" , description = "批量下线商品")
    public ServerResponseEntity<Void> batchOffline(@RequestBody OfflineHandleEventDTO offlineHandleEventDto) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        if (CollUtil.isEmpty(offlineHandleEventDto.getHandleIds())) {
            throw new LuckException("下线的商品id列表不能为空");
        }
        spuService.batchOffile(offlineHandleEventDto);
        return ServerResponseEntity.success();
    }

    @GetMapping("/get_offline_handle_event/{spuId}")
    @Operation(summary = "获取最新下线的事件" , description = "获取最新下线的事件")
    public ServerResponseEntity<OfflineHandleEventVO> getOfflineHandleEvent(@PathVariable Long spuId) {
        SpuVO spuDb = spuService.getBySpuId(spuId);
        if (!Objects.equals(spuDb.getShopId(), AuthUserContext.get().getTenantId()) && !Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId()) ) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        return ServerResponseEntity.success(spuService.getOfflineHandleEvent(spuId));
    }

//    @GetMapping("/page_can_seckill_prod")
//    @Operation(summary = "获取可以参与秒杀活动的商品分页列表" , description = "可以参与秒杀活动的商品分页列表")
//    public ServerResponseEntity<PageVO<SpuVO>> pageCanSeckillProd(@Valid PageDTO pageDTO,SpuDTO spuDTO) {
//        spuDTO.setShopId(AuthUserContext.get().getTenantId());
//        return ServerResponseEntity.success(spuService.pageCanSeckillProd(pageDTO, spuDTO));
//    }

    @PostMapping("/audit")
    @Operation(summary = "审核商品" , description = "审核商品")
    public ServerResponseEntity<Void> audit(@RequestBody OfflineHandleEventDTO offlineHandleEventDto) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        spuService.audit(offlineHandleEventDto);
        spuService.removeSpuCacheBySpuId(offlineHandleEventDto.getHandleId());
        return ServerResponseEntity.success();
    }

    @PostMapping("/audit_apply")
    @Operation(summary = "违规活动提交审核" , description = "违规活动提交审核")
    public ServerResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventDTO offlineHandleEventDto) {
        SpuVO spuDb = spuService.getBySpuId(offlineHandleEventDto.getHandleId());
        if (!Objects.equals(spuDb.getShopId(), AuthUserContext.get().getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        spuService.auditApply(offlineHandleEventDto);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getSupplierInfoByspuId")
    @Operation(summary = "商家编辑商品时获取供应商商品信息" , description = "商家编辑商品时获取供应商商品信息")
    public ServerResponseEntity<SupplierSpuVo> getSupplierInfoBySpuId(Long supplierSpuId){
        Long shopId = AuthUserContext.get().getTenantId();
        //供应商商品信息
        SupplierSpuVo supplierInfo = spuService.getSupplierInfoBySpuId(supplierSpuId,shopId);
        //属性
        supplierInfo.setSpuAttrValues(spuAttrValueService.getSpuAttrsBySpuId(supplierSpuId));
        // 平台分类、店铺分类信息
        supplierInfo.setCategory(categoryService.getInfo(supplierInfo.getCategoryId()));
        // 品牌信息
        supplierInfo.setBrand(brandService.getByBrandId(supplierInfo.getBrandId()));
        if (Objects.nonNull(supplierInfo.getShopCategoryId()) && !Objects.equals(supplierInfo.getShopCategoryId(), Constant.DEFAULT_ID)) {
            supplierInfo.setShopCategory(categoryService.getInfo(supplierInfo.getShopCategoryId()));
        }
        //获取店铺
        return ServerResponseEntity.success(supplierInfo);
    }


    @PostMapping("/importSupplierSpu")
    @Operation(summary = "商家单个/批量导入供应商商品" , description = "商家单个/批量导入供应商商品")
    public ServerResponseEntity<Void> importSupplierSpu(@RequestBody List<Long> supplierSpuId){
        spuService.importSupplierSpu(supplierSpuId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/supplier_excel")
    @Operation(summary = "代销商品导出excel" , description = "导出商品excel")
    public ServerResponseEntity<Void> SupplierSpuSoldExcel(HttpServletResponse response, @ParameterObject SpuPageSearchDTO spuDTO) {
        List<SupplierSpuExcelVO> list = spuExcelService.excelSupplierSpuList(spuDTO);
        ExcelUtil.soleExcelWithHandler(response, list, SupplierSpuExcelVO.EXCEL_NAME, SupplierSpuExcelVO.MERGE_ROW_INDEX,
                SupplierSpuExcelVO.MERGE_COLUMN_INDEX, new ProductCommentWriteHandler(null), SupplierSpuExcelVO.class);
        return ServerResponseEntity.success();
    }
}
